package com.argesone.third.shanxiyingji.loginadapter.controller;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.symmetric.AES;
import cn.hutool.extra.spring.SpringUtil;
import com.argesone.third.shanxiyingji.loginadapter.config.TowerLoginConfig;
import com.argesone.third.shanxiyingji.loginadapter.entity.User;
import com.argesone.third.shanxiyingji.loginadapter.service.IAuthService;
import com.flyfish.oauth.common.sync.SyncSender;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.Collections;
import java.util.List;


@Slf4j
@Controller
public class AuthController {
    @Autowired
    private TowerLoginConfig towerLoginConfig;

    @GetMapping
    public String index(HttpServletRequest request) {
        User userInfo = (User) request.getSession().getAttribute("user");
        if (null == userInfo) {
            return "redirect:" + towerLoginConfig.getUrl();
        }
        IAuthService iAuthService = SpringUtil.getBean(IAuthService.class);
        String loginUrl = iAuthService.getTowerPortalLoginUrl(userInfo);
        //如果地址不包含问号，就到登录页面
        if (!loginUrl.contains("?")) {
            return "resetPassword";
        }
        return "redirect:" + loginUrl;
    }

    @PostMapping("resetPassword")
    public String resetPassword(String password, HttpServletRequest request) {
        User userInfo = (User) request.getSession().getAttribute("user");
        userInfo.setPassword(SecureUtil.aes(towerLoginConfig.getPasswordSecretKey().getBytes()).encryptBase64(password));
        boolean send = SyncSender.send(Collections.singletonList(userInfo));
        log.info("--->>> send: {}", send);
        return "redirect:/";
    }


    @ResponseBody
    @PostMapping("/synUser")
    public boolean synUser(@RequestBody List<User> userinfo) {
        AES aes = SecureUtil.aes(towerLoginConfig.getPasswordSecretKey().getBytes());

        userinfo.forEach(user -> {
            if (StrUtil.isNotBlank(user.getPassword())) {
                user.setPassword(aes.encryptBase64(user.getPassword()));
            }
        });

        return SyncSender.send(userinfo);
    }
}
